package net.xuele.learn.exchanger;

import java.util.concurrent.SynchronousQueue;

public class TestSynchronousQueue {

    static class Producer extends Thread {
        private SynchronousQueue synchronousQueue;

        Producer(String name, SynchronousQueue synchronousQueue) {
            super("Producer-" + name);
            this.synchronousQueue = synchronousQueue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 2; i++) {
                try {
                    synchronousQueue.put("produce something " + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static class Consumer extends Thread {
        private SynchronousQueue synchronousQueue;

        Consumer(String name, SynchronousQueue synchronousQueue) {
            super("Producer-" + name);
            this.synchronousQueue = synchronousQueue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 2; i++) {
                System.out.println(synchronousQueue.poll());
            }
        }
    }

    public static void main(String[] args) {
        SynchronousQueue synchronousQueue = new SynchronousQueue(true);
        new TestSynchronousQueue.Producer("A", synchronousQueue).start();
        new TestSynchronousQueue.Consumer("A", synchronousQueue).start();
    }

}
